'''
Game controller
'''
import pygame

class Controller:
    
    def __init__(self):
        self.is_listening = False
        self.position = None
        
    
    def pass_(self):
        pass
    
    def get_stone_position(self, posicion, board):
    
        if (posicion[0] < board.delta[0] or posicion[1] < board.delta[1]):
            return (-1, -1)
        
        x = posicion[0] - board.delta[0] - board.empty_size_x
        y = posicion[1] - board.delta[1] - board.empty_size_y
        
        pos_x = x / board.dx
        pos_y = y / board.dy
        
        pos_x += 0.5
        pos_y += 0.5
        
        return (int(pos_x) + 1, int(pos_y) + 1)

    def check_window_not_moved(self, first_position, last_position):
    
        deltaX, deltaY = first_position[0] - last_position[0], first_position[1] - last_position[1]
        
        if (deltaX < 0):
            deltaX = -1 * deltaX
        
        if (deltaY < 0):
            deltaY = -1 * deltaY
            
        return not (deltaX > 5 or deltaY > 5)
    
    def transform_coordinates(self, posRaton, posContenedor):
    
        x1, x2 = posRaton[0], posContenedor[0]
        y1, y2 = posRaton[1], posContenedor[1] 
        
        if (x2 < 0):
            x1 -= x2
            x2 = 0
            
        if (y2 < 0):
            y1 -= y2
            y2 = 0    
        
        return x1 - x2, y1 - y2 
    
    def invert_coordinates(self, nueva_ficha, window):
        y = window.board.boardSize - nueva_ficha[1]
        x = nueva_ficha[0] - 1
        return (x, y) 
                
    def on_click(self, window):
        if self.is_listening:
                 
            mouse_pos = pygame.mouse.get_pos()    
            if self.check_window_not_moved(window.first_position, mouse_pos):
                coordinates = self.transform_coordinates(mouse_pos, window.position)
               
                nueva_ficha = self.get_stone_position(coordinates, window.board)
                    
                if nueva_ficha != (-1, -1):    
                    nueva_ficha = self.invert_coordinates(nueva_ficha, window)
                        
                    self.position = nueva_ficha
                    self.is_listening = False
                
        
            
